/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.client.editor.controller;

import java.awt.event.ActionEvent;

import java.util.HashSet;
import javax.swing.text.AbstractDocument.LeafElement;
import javax.swing.text.Element;
import javax.swing.tree.DefaultMutableTreeNode;

import javax.swing.tree.TreePath;
import offset.nodes.client.editor.Editor;
import offset.nodes.client.editor.controller.ParagraphActions.AbstractParagraphAction;
import offset.nodes.client.editor.model.DocumentContext;
import offset.nodes.client.editor.model.EditorDocument;
import offset.nodes.client.editor.model.ParagraphModel;
import offset.nodes.client.editor.model.Range;
import offset.nodes.client.editor.view.Heading;
import offset.nodes.client.editor.view.PopupTree;
import offset.nodes.client.editor.view.StyleClassDialog;

public class ParagraphActions {

    public static abstract class AbstractParagraphAction extends EditorActions.AbstractEditorAction {

        public AbstractParagraphAction(String name, Editor editor) {
            super(name, editor);
        }

        protected ParagraphModel getModel(ActionEvent ae) {
            return new ParagraphModel(getDocumentContext(ae));
        }

        protected ParagraphModel getModel(Editor editor) {
            return new ParagraphModel(new DocumentContext(getEditor().getBrowserPane()));
        }

    }

    public static class InsertHeading1Action extends AbstractParagraphAction {

        public void action(ActionEvent e) throws Exception {
            Range range = new Range(getEditor(e).getSelectionStart(), getEditor(e).getSelectionEnd());
            getModel(e).setHeading(range, 1);
            refreshCaret(e, range);
        }

        public InsertHeading1Action(Editor editor) {
            super(java.util.ResourceBundle.getBundle("offset/nodes/client/editor/view/resources/EditorBundle").getString("Heading_1"), editor);
            //setName(java.util.ResourceBundle.getBundle("offset/nodes/client/editor/view/resources/EditorBundle").getString("Heading_1"));
            setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_1, java.awt.event.InputEvent.CTRL_MASK));
            setIcon(new javax.swing.ImageIcon(getClass().getResource("/offset/nodes/client/editor/view/resources/sc_heading_1.png")));
        }
    }

    public static class InsertHeading2Action extends AbstractParagraphAction {

        public void action(ActionEvent e) throws Exception {
            Range range = new Range(getEditor(e).getSelectionStart(), getEditor(e).getSelectionEnd());
            getModel(e).setHeading(range, 2);
            refreshCaret(e, range);
        }

        public InsertHeading2Action(Editor editor) {
            super(java.util.ResourceBundle.getBundle("offset/nodes/client/editor/view/resources/EditorBundle").getString("Heading_2"), editor);
            //setName(java.util.ResourceBundle.getBundle("offset/nodes/client/editor/view/resources/EditorBundle").getString("Heading_2"));
            setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_2, java.awt.event.InputEvent.CTRL_MASK));
            setIcon(new javax.swing.ImageIcon(getClass().getResource("/offset/nodes/client/editor/view/resources/sc_heading_2.png")));
        }
    }

    public static class InsertHeading3Action extends AbstractParagraphAction {

        public void action(ActionEvent e) throws Exception {
            Range range = new Range(getEditor(e).getSelectionStart(), getEditor(e).getSelectionEnd());
            getModel(e).setHeading(range, 3);
            refreshCaret(e, range);
        }

        public InsertHeading3Action(Editor editor) {
            super(java.util.ResourceBundle.getBundle("offset/nodes/client/editor/view/resources/EditorBundle").getString("Heading_3"), editor);
            setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_3, java.awt.event.InputEvent.CTRL_MASK));
        }
    }

    public static class InsertHeading4Action extends AbstractParagraphAction {

        public void action(ActionEvent e) throws Exception {
            Range range = new Range(getEditor(e).getSelectionStart(), getEditor(e).getSelectionEnd());
            getModel(e).setHeading(range, 4);
            refreshCaret(e, range);
        }

        public InsertHeading4Action(Editor editor) {
            super(java.util.ResourceBundle.getBundle("offset/nodes/client/editor/view/resources/EditorBundle").getString("Heading_4"), editor);
            setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_4, java.awt.event.InputEvent.CTRL_MASK));
        }
    }

    public static class InsertHeading5Action extends AbstractParagraphAction {

        public void action(ActionEvent e) throws Exception {
            Range range = new Range(getEditor(e).getSelectionStart(), getEditor(e).getSelectionEnd());
            getModel(e).setHeading(range, 5);
            refreshCaret(e, range);
        }

        public InsertHeading5Action(Editor editor) {
            super(java.util.ResourceBundle.getBundle("offset/nodes/client/editor/view/resources/EditorBundle").getString("Heading_5"), editor);
            setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_5, java.awt.event.InputEvent.CTRL_MASK));
        }
    }

    public static class InsertHeading6Action extends AbstractParagraphAction {

        public void action(ActionEvent e) throws Exception {
            Range range = new Range(getEditor(e).getSelectionStart(), getEditor(e).getSelectionEnd());
            getModel(e).setHeading(range, 6);
            refreshCaret(e, range);
        }

        public InsertHeading6Action(Editor editor) {
            super(java.util.ResourceBundle.getBundle("offset/nodes/client/editor/view/resources/EditorBundle").getString("Heading_6"), editor);
            setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_6, java.awt.event.InputEvent.CTRL_MASK));
        }
    }

    public static class InsertStandardAction extends AbstractParagraphAction {

        public void action(ActionEvent e) throws Exception {
            Range range = new Range(getEditor(e).getSelectionStart(), getEditor(e).getSelectionEnd());
            getModel(e).setParagraph(range, "p");
            refreshCaret(e, range);
        }

        public InsertStandardAction(Editor editor) {
            super(java.util.ResourceBundle.getBundle("offset/nodes/client/editor/view/resources/EditorBundle").getString("Standard"), editor);
            setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        }
    }

    public static class InsertCodeAction extends AbstractParagraphAction {

        public void action(ActionEvent e) throws Exception {
            Range range = new Range(getEditor(e).getSelectionStart(), getEditor(e).getSelectionEnd());
            getModel(e).setParagraph(range, "pre");
            refreshCaret(e, range);
        }

        public InsertCodeAction(Editor editor) {
            super(java.util.ResourceBundle.getBundle("offset/nodes/client/editor/view/resources/EditorBundle").getString("codeParagraph"), editor);
            setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
            setIcon(new javax.swing.ImageIcon(getClass().getResource("/offset/nodes/client/editor/view/resources/sc_code.png")));
        }
    }

    public static class AddStyleAction extends AbstractParagraphAction {

        public void action(ActionEvent e) throws Exception {
            StyleClassDialog dialog = new StyleClassDialog(null, true, (EditorDocument) editor.getBrowserPane().getDocument());
            dialog.setVisible(true);
            if (dialog.getReturnStatus() == StyleClassDialog.RET_OK) {
                Range range = new Range(getEditor(e).getSelectionStart(), getEditor(e).getSelectionEnd());
                getModel(e).setStyle(range, dialog.getSelectedStyleClassName(), dialog.isClassStyle());
                refreshCaret(e, range);
            }
        }

        public AddStyleAction(Editor editor) {
            super(java.util.ResourceBundle.getBundle("offset/nodes/client/editor/view/resources/EditorBundle").getString("addStyle"), editor);
            setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        }
    }
    
    public static class NonInlinePopupItem extends PopupTree.AbstractPopupItem {

        public NonInlinePopupItem(Editor editor, AbstractParagraphAction action) {
            super(editor, action);
        }

        public boolean isItemNode(PopupTree.PopupNode node) {
            if (!(node.getUserObject() instanceof Element))
                return false;
            
            Element e = (Element) node.getUserObject();
            if (e instanceof LeafElement) {
                return false;
            }

            return true;
        }
    }

    public static PopupTree.NodePopup[] getParagraphHeadingPopups(Editor editor) {
        return new PopupTree.NodePopup[]{
                    new PopupTree.ItemGroupsPopup(
                    new PopupTree.ItemGroup[]{
                        new PopupTree.ItemGroup(
                        new PopupTree.PopupItem[]{
                            new NonInlinePopupItem(editor, new HeadingLevelAction(editor))
                        }),
                        new PopupTree.ItemGroup(
                        new PopupTree.PopupItem[]{
                            new NonInlinePopupItem(editor, new HeadingUpAction(editor)),
                            new NonInlinePopupItem(editor, new HeadingDownAction(editor))
                        }),
                        new PopupTree.ItemGroup(
                        new PopupTree.PopupItem[]{
                            new NonInlinePopupItem(editor, new HeadingRightIndentAction(editor)),
                            new NonInlinePopupItem(editor, new HeadingLeftIndentAction(editor))
                        })
                    })
                };
    }

    public static PopupTree.NodePopup[] getParagraphStructurePopups(Editor editor) {
        return new PopupTree.NodePopup[]{
                    new PopupTree.ItemGroupsPopup(
                    new PopupTree.ItemGroup[]{
                        new PopupTree.ItemGroup(
                        new PopupTree.PopupItem[]{
                            new NonInlinePopupItem(editor, new InsertParagraphAction(editor)),
                            new NonInlinePopupItem(editor, new AddParagraphAction(editor)),
                            new NonInlinePopupItem(editor, new RemoveElementAction(editor)),
                            new NonInlinePopupItem(editor, new CreateDivAction(editor))
                        }),
                        new PopupTree.ItemGroup(
                        new PopupTree.PopupItem[]{
                            new NonInlinePopupItem(editor, new AddStyleToElementAction(editor)),
                            new NonInlinePopupItem(editor, new RemoveStyleFromElementAction(editor))
                        })
                    })
                };
    }

    public static class HeadingLevelAction extends AbstractParagraphAction {

        public void action(ActionEvent e) throws Exception {
            if (getEditor().getHeadingTree().getSelectionCount() <= 0) {
                return;
            }

            DefaultMutableTreeNode node = (DefaultMutableTreeNode) getEditor().getHeadingTree().getSelectionPath().getLastPathComponent();

            Range range = new Range(getEditor().getBrowserPane().getSelectionStart(), getEditor().getBrowserPane().getSelectionEnd());
            //getModel(editor).headingRightIndent((Element)node.getUserObject());
            refreshCaret(editor, range);
        }

        public HeadingLevelAction(Editor editor) {
            super(java.util.ResourceBundle.getBundle("offset/nodes/client/editor/view/resources/EditorBundle").getString("HeadingLevel"), editor);
            setIcon(new javax.swing.ImageIcon(getClass().getResource("/offset/nodes/client/editor/view/resources/heading-level.png")));
        }
    }

    public static class HeadingRightIndentAction extends AbstractParagraphAction {

        public void action(ActionEvent e) throws Exception {
            if (getEditor().getHeadingTree().getSelectionCount() <= 0) {
                return;
            }

            DefaultMutableTreeNode node = (DefaultMutableTreeNode) getEditor().getHeadingTree().getSelectionPath().getLastPathComponent();

            Range range = new Range(getEditor().getBrowserPane().getSelectionStart(), getEditor().getBrowserPane().getSelectionEnd());
            Heading heading = (Heading) node.getUserObject();
            if (heading != null) {
                getModel(editor).headingRightIndent(heading.getElement());
            }
            refreshCaret(editor, range);
        }

        public HeadingRightIndentAction(Editor editor) {
            super(java.util.ResourceBundle.getBundle("offset/nodes/client/editor/view/resources/EditorBundle").getString("RightIndentHeading"), editor);
            setIcon(new javax.swing.ImageIcon(getClass().getResource("/offset/nodes/client/editor/view/resources/heading-right.png")));
        }
    }

    public static class HeadingLeftIndentAction extends AbstractParagraphAction {

        public void action(ActionEvent e) throws Exception {
            if (getEditor().getHeadingTree().getSelectionCount() <= 0) {
                return;
            }

            DefaultMutableTreeNode node = (DefaultMutableTreeNode) getEditor().getHeadingTree().getSelectionPath().getLastPathComponent();

            Range range = new Range(getEditor().getBrowserPane().getSelectionStart(), getEditor().getBrowserPane().getSelectionEnd());
            Heading heading = (Heading) node.getUserObject();
            if (heading != null) {
                getModel(editor).headingLeftIndent(heading.getElement());
            }
            refreshCaret(editor, range);
        }

        public HeadingLeftIndentAction(Editor editor) {
            super(java.util.ResourceBundle.getBundle("offset/nodes/client/editor/view/resources/EditorBundle").getString("LeftIndentHeading"), editor);
            setIcon(new javax.swing.ImageIcon(getClass().getResource("/offset/nodes/client/editor/view/resources/heading-left.png")));
        }
    }

    public static class HeadingUpAction extends AbstractParagraphAction {

        public void action(ActionEvent e) throws Exception {
            if (getEditor().getHeadingTree().getSelectionCount() <= 0) {
                return;
            }

            DefaultMutableTreeNode node = (DefaultMutableTreeNode) getEditor().getHeadingTree().getSelectionPath().getLastPathComponent();

            Range range = new Range(getEditor().getBrowserPane().getSelectionStart(), getEditor().getBrowserPane().getSelectionEnd());
            Heading heading = (Heading) node.getUserObject();
            if (heading != null) {
                getModel(editor).headingUp(heading.getElement());
            }
            refreshCaret(editor, range);
        }

        public HeadingUpAction(Editor editor) {
            super(java.util.ResourceBundle.getBundle("offset/nodes/client/editor/view/resources/EditorBundle").getString("HeadingUp"), editor);
            setIcon(new javax.swing.ImageIcon(getClass().getResource("/offset/nodes/client/editor/view/resources/heading-up.png")));
        }
    }

    public static class HeadingDownAction extends AbstractParagraphAction {

        public void action(ActionEvent e) throws Exception {
            if (getEditor().getHeadingTree().getSelectionCount() <= 0) {
                return;
            }

            DefaultMutableTreeNode node = (DefaultMutableTreeNode) getEditor().getHeadingTree().getSelectionPath().getLastPathComponent();

            Range range = new Range(getEditor().getBrowserPane().getSelectionStart(), getEditor().getBrowserPane().getSelectionEnd());
            Heading heading = (Heading) node.getUserObject();
            if (heading != null) {
                getModel(editor).headingDown(heading.getElement());
            }
            refreshCaret(editor, range);
        }

        public HeadingDownAction(Editor editor) {
            super(java.util.ResourceBundle.getBundle("offset/nodes/client/editor/view/resources/EditorBundle").getString("HeadingDown"), editor);
            setIcon(new javax.swing.ImageIcon(getClass().getResource("/offset/nodes/client/editor/view/resources/heading-down.png")));
        }
    }

    public static class CreateDivAction extends AbstractParagraphAction {

        public void action(ActionEvent e) throws Exception {
            if (getEditor().getStructureTree().getSelectionCount() == 0) {
                return;
            }

            TreePath[] paths = getEditor().getStructureTree().getSelectionPaths();

            DefaultMutableTreeNode parent = null;
            DefaultMutableTreeNode previous = null;
            int max = 0;
            int min = Integer.MAX_VALUE;
            for (int i = 0; i < paths.length; i++) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) paths[i].getLastPathComponent();
                if (parent != null && (!parent.isNodeChild(node) || parent.getIndex(node) != parent.getIndex(previous) + 1)) {
                    return;
                } // div only for contiguous siblings

                if (parent == null) {
                    parent = (DefaultMutableTreeNode) node.getParent();
                }
                previous = node;

                int index = parent.getIndex(node);
                if (index < min) {
                    min = index;
                }
                if (index > max) {
                    max = index;
                }
            }

            getModel(editor).createContainerDiv((Element) parent.getUserObject(), min, max);
        }

        public CreateDivAction(Editor editor) {
            super(java.util.ResourceBundle.getBundle("offset/nodes/client/editor/view/resources/EditorBundle").getString("CreateDiv"), editor);
        }
    }

    public static class AddParagraphAction extends AbstractParagraphAction {

        public void action(ActionEvent e) throws Exception {
            if (getEditor().getStructureTree().getSelectionCount() <= 0) {
                return;
            }

            DefaultMutableTreeNode node = (DefaultMutableTreeNode) getEditor().getStructureTree().getSelectionPath().getLastPathComponent();
            getModel(editor).addParagraphAfterElement((Element) node.getUserObject());

        }

        public AddParagraphAction(Editor editor) {
            super(java.util.ResourceBundle.getBundle("offset/nodes/client/editor/view/resources/EditorBundle").getString("AddParagraph"), editor);
        }
    }

    public static class InsertParagraphAction extends AbstractParagraphAction {

        public void action(ActionEvent e) throws Exception {
            if (getEditor().getStructureTree().getSelectionCount() <= 0) {
                return;
            }

            DefaultMutableTreeNode node = (DefaultMutableTreeNode) getEditor().getStructureTree().getSelectionPath().getLastPathComponent();
            getModel(editor).addParagraphBeforeElement((Element) node.getUserObject());

        }

        public InsertParagraphAction(Editor editor) {
            super(java.util.ResourceBundle.getBundle("offset/nodes/client/editor/view/resources/EditorBundle").getString("InsertParagraph"), editor);
        }
    }

    public static class RemoveElementAction extends AbstractParagraphAction {

        public void action(ActionEvent e) throws Exception {
            if (getEditor().getStructureTree().getSelectionCount() <= 0) {
                return;
            }

            if (getEditor().getStructureTree().getSelectionCount() > 1) {
                TreePath[] selected = getEditor().getStructureTree().getSelectionPaths();
                boolean sameParent = true;
                for (int i = 1; i < selected.length; i++)
                    if (!selected[0].getParentPath().equals(selected[i].getParentPath())) {
                        sameParent = false;
                        break;
                    }

                if (sameParent) {
                    Element parent = null;
                    HashSet<Element> selectedElements = new HashSet<Element>();
                    for (TreePath selectedPath : selected) {
                        DefaultMutableTreeNode node = (DefaultMutableTreeNode) selectedPath.getLastPathComponent();
                        Element element = (Element) node.getUserObject();
                        selectedElements.add(element);
                        if (parent == null)
                            parent = element.getParentElement();
                    }

                    getModel(editor).removeChildren(parent, selectedElements);
                    return;
                }
            }

            DefaultMutableTreeNode node = (DefaultMutableTreeNode) getEditor().getStructureTree().getSelectionPath().getLastPathComponent();
            getModel(editor).remove((Element) node.getUserObject());

        }

        public RemoveElementAction(Editor editor) {
            super(java.util.ResourceBundle.getBundle("offset/nodes/client/editor/view/resources/EditorBundle").getString("RemoveElement"), editor);
        }
    }

    public static class AddStyleToElementAction extends AbstractParagraphAction {

        public void action(ActionEvent e) throws Exception {
            if (getEditor().getStructureTree().getSelectionCount() <= 0) {
                return;
            }

            StyleClassDialog dialog = new StyleClassDialog(null, true, (EditorDocument) editor.getBrowserPane().getDocument());
            dialog.setVisible(true);
            if (dialog.getReturnStatus() == StyleClassDialog.RET_OK) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) getEditor().getStructureTree().getSelectionPath().getLastPathComponent();
                getModel(editor).setStyle((Element) node.getUserObject(), dialog.getSelectedStyleClassName(), dialog.isClassStyle());
            }

        }

        public AddStyleToElementAction(Editor editor) {
             super(java.util.ResourceBundle.getBundle("offset/nodes/client/editor/view/resources/EditorBundle").getString("addStyle"), editor);
      }
    }


    public static class RemoveStyleFromElementAction extends AbstractParagraphAction {

        public void action(ActionEvent e) throws Exception {
            if (getEditor().getStructureTree().getSelectionCount() <= 0)
                return;

            DefaultMutableTreeNode node = (DefaultMutableTreeNode) getEditor().getStructureTree().getSelectionPath().getLastPathComponent();
            getModel(editor).removeStyle((Element) node.getUserObject());
        }

        public RemoveStyleFromElementAction(Editor editor) {
             super(java.util.ResourceBundle.getBundle("offset/nodes/client/editor/view/resources/EditorBundle").getString("removeStyle"), editor);
      }
    }



 }
